<template>
  <div class="upload-file">
    <el-upload multiple :action="uploadFileUrl" :before-upload="handleBeforeUpload" :file-list="fileList" :limit="limit"
      :on-error="handleUploadError" :on-exceed="handleExceed" :on-success="handleUploadSuccess" :show-file-list="false"
      :headers="headers" class="upload-file-uploader" ref="fileUpload">
      <!-- 上传按钮 -->
      <el-button size="mini" type="primary">选取文件</el-button>
      <!-- 上传提示 -->
      <div class="el-upload__tip" slot="tip" v-if="showTip">
        请上传
        <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
        <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
        的文件
      </div>
    </el-upload>

    <!-- 文件列表 -->
    <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
      <li :key="file.url" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList">
        <el-link :href="file.url" :underline="false" target="_blank">
          <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
        </el-link>
        <div class="ele-upload-list__item-content-action">
          <el-link :underline="false" @click="handleDelete(index)" type="danger">删除</el-link>
        </div>
      </li>
    </transition-group>
  </div>
</template>

<script setup lang="ts">
import { tokenUtils } from '@gyk/gyk-utils';
import { ref, watch, computed, getCurrentInstance } from 'vue';
import { ElMessage } from 'element-plus';

const app = getCurrentInstance();
const imageUpload = ref();

const defProps = withDefaults(defineProps<{
  modelValue: any,
  // 图片数量限制
  limit?: number,
  // 大小限制(MB)
  fileSize?: number,
  // 文件类型限制
  fileType?: string[],
  // 是否显示提示
  isShowTip?: boolean,
}>(), {
  limit: 5,
  fileSize: 5,
  fileType: () => ["doc", "xls", "ppt", "txt", "pdf"],
  isShowTip: true,
})

let LoadingInstance;
const number = ref(0);
const uploadList = ref<any>([]);

// 上传的图片服务器地址
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + '/file/upload');
// 请求头
const headers = {
  Authorization: "Bearer " + tokenUtils.getToken(),
}
// 文件列表
const fileList = ref<any>([]);

// 监听
watch(
  () => defProps.modelValue,
  (val) => {
    if (val) {
      // 首先将值转为数组
      const list = Array.isArray(val) ? val : defProps.modelValue.split(',');
      // 然后将数组转为对象数组
      fileList.value = list.map(item => {
        if (typeof item === "string") {
          item = { name: item, url: item };
        }
        return item;
      });
    } else {
      fileList.value = [];
      return [];
    }
  },
  { deep: true, immediate: true }
);

// 触发事件
const emits = defineEmits<{
  (e: 'input', listString: string): void,
}>();

const showTip = computed(() => {
  return defProps.isShowTip && (defProps.fileType || defProps.fileSize);
})

// 上传前loading加载
function handleBeforeUpload(file) {
  let isImg = false;
  if (defProps.fileType.length) {
    let fileExtension = "";
    if (file.name.lastIndexOf(".") > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
    }
    isImg = defProps.fileType.some(type => {
      if (file.type.indexOf(type) > -1) return true;
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });
  } else {
    isImg = file.type.indexOf("image") > -1;
  }

  if (!isImg) {
    ElMessage({ message: `文件格式不正确, 请上传${defProps.fileType.join("/")}格式文件!`, type: 'error' })
    return false;
  }
  if (defProps.fileSize) {
    const isLt = file.size / 1024 / 1024 < defProps.fileSize;
    if (!isLt) {
      ElMessage({ message: `上传文件大小不能超过 ${defProps.fileSize} MB!`, type: 'error' })
      return false;
    }
  }
  LoadingInstance = app?.proxy?.$loading({ fullscreen: true, text: "正在上传文件，请稍候..." });
  number.value++;
}
// 文件个数超出
function handleExceed() {
  ElMessage({ message: `上传文件数量不能超过 ${defProps.limit} 个!`, type: 'error' })
}
// 上传成功回调
function handleUploadSuccess(res, file) {
  if (res.code === 200) {
    uploadList.value.push({ name: res.data.url, url: res.data.url });
    uploadedSuccessfully();
  } else {
    number.value--;
    if (LoadingInstance) {
      LoadingInstance.close()
    }
    ElMessage({ message: res.msg, type: 'success' })
    imageUpload.value.handleRemove(file);
    uploadedSuccessfully();
  }
}

// 删除图片
function handleDelete(file) {
  const findex = fileList.value.map(f => f.name).indexOf(file.name);
  if (findex > -1) {
    fileList.value.splice(findex, 1);
    emits("input", listToString(fileList.value));
  }
}

// 上传失败
function handleUploadError() {
  ElMessage({ message: "上传图片失败，请重试", type: 'error' })
  if (LoadingInstance) {
    LoadingInstance.close()
  }
}

// 上传结束处理
function uploadedSuccessfully() {
  if (number.value > 0 && uploadList.value.length === number.value) {
    fileList.value = fileList.value.concat(uploadList.value);
    uploadList.value = [];
    number.value = 0;
    emits("input", listToString(fileList.value));
    if (LoadingInstance) {
      LoadingInstance.close()
    }
  }
}

// 获取文件名称
function getFileName(name) {
  if (name.lastIndexOf("/") > -1) {
    return name.slice(name.lastIndexOf("/") + 1);
  } else {
    return "";
  }
}

// 对象转成指定字符串分隔
function listToString(list: any, separator?: string) {
  let strs = "";
  separator = separator || ",";
  for (let i in list) {
    if (list[i].url) {
      strs += list[i].url.replace + separator;
    }
  }
  return strs != '' ? strs.substring(0, strs.length - 1) : '';
}
</script>

<style lang="scss" scoped></style>